
<template>
    <div>
		<el-dialog draggable :title="title" :width="810"
			v-model="show" :close-on-click-modal="false" @close="emit('update:show', false)">
			<div class="dialog-content">
          <div class="toolbar tool-query">
            <el-row :gutter="0">
              <el-col :xs="8" :sm="4" class="col-title">表名</el-col>
              <el-col :xs="16" :sm="8" class="col-content">
                <el-input placeholder="" v-model="dataForm.TABLE_NAME" size="small"></el-input>
              </el-col>
            </el-row>
          </div>
          <el-row :gutter="0" style="padding:10px;text-align:center;">
              <el-col :xs="4" :sm="1" class="col-title">
                 <el-button type="success" :icon="Plus" circle size="small" @click="handleAddRow" />
              </el-col>
          </el-row>
		  <el-table :data="dataForm.Columns" style="width: 100%" height="300px" size="small" empty-text="无数据">
            <el-table-column label="" width="48">
              <template #default="scope"> 
                <el-button type="danger" :icon="Edit" circle size="small" @click="handleRemove(scope)" />
              </template>
            </el-table-column>
            <el-table-column prop="ISKEY" label="键" width="40" align="center">
              <template #default="scope"> 
                <el-checkbox v-model="scope.row.ISKEY" :true-label="1" :false-label="0" size="small" 
                @change="()=>{ if(scope.row.ISKEY == 0 || scope.row.DATA_TYPE != 'integer') scope.row.AUTOIN = 0 }"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="AUTOIN" label="自增" width="40" align="center">
              <template #default="scope"> 
                <el-checkbox v-model="scope.row.AUTOIN" :true-label="1" :false-label="0" size="small" 
                :disabled="scope.row.ISKEY != 1 || scope.row.DATA_TYPE != 'integer'"
                @change="val=>{if(val){scope.row.NULLABLE='N'}}"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="COLUMN_NAME" label="列名" width="180">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.COLUMN_NAME" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_TYPE" label="类型" width="140">
              <template #default="scope">
                  <el-select v-model="scope.row.DATA_TYPE" placeholder="请选择" size="small" @change="()=>{
                    scope.row.DATA_LENGTH =''
                    scope.row.DATA_SCALE = ''
                    if(scope.row.DATA_TYPE != 'real') 
                       scope.row.DATA_SCALE=''
                    if(scope.row.ISKEY == 0 || scope.row.DATA_TYPE != 'integer') 
                       scope.row.AUTOIN = 0
                    }">
                    <el-option key="text" label="text" value="text"></el-option>
                    <el-option key="integer" label="integer" value="integer"></el-option>
                    <el-option key="real" label="real" value="real"></el-option>
                    <el-option key="blob" label="blob" value="blob"></el-option>
                  </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_LENGTH" label="长度" width="85">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.DATA_LENGTH" size="small"
                   ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_SCALE" label="小数位" width="85">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.DATA_SCALE" size="small" :disabled="scope.row.DATA_TYPE != 'real'" ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_DEFAULT" label="默认值" width="100">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.DATA_DEFAULT" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="NULLABLE" label="非空" width="45" align="center">
              <template #default="scope">
                <el-checkbox v-model="scope.row.NULLABLE" true-label="N" false-label="Y" size="small"></el-checkbox>
              </template>
            </el-table-column>
          </el-table>
			</div>
			<template #footer>
          <span class="dialog-footer">
              <el-button size="small" @click="emit('update:show', false)">取消</el-button>
              <el-button size="small" type="primary" @click="submitForm">
                  提交</el-button>
          </span>
			</template>
		</el-dialog>
    </div>
</template>
<style scoped>
  .tool-query {
	border: 1px solid #ddd;
    line-height: 37px;
    border-radius: 5px;
  }
  .tool-query .col-title {
	  padding: 0 10px
  }
</style>
<script setup>
import { Plus, Edit } from '@element-plus/icons-vue'
import { post } from '/src/utils/http'
import { ElMessage } from 'element-plus'
import { watch,defineProps, defineEmits, onMounted, toRefs, nextTick, ref, computed } from 'vue'

const props = defineProps({
  show:Boolean,
  dbName: String,
  tableName: String,
  dbConnStr: String
})

const { show,dbName,tableName,dbConnStr } = toRefs(props)

const emit = defineEmits(['update:show'])

const title = computed(() => tableName.value ? '编辑': '新建')

const dataForm = ref({
      DbType: 'Sqlite',
      TABLE_NAME: '',
      EDIT_TABLE_NAME: '',
      Columns:[],
  })
const ColumnDefalut = ref({
      ISKEY: 0,
      EDIT_COLUMN_NAME: '',
      COLUMN_NAME: '',
      DATA_TYPE: 'text',
      DATA_LENGTH: '', 
      DATA_SCALE: '',
      DATA_DEFAULT: '',
      NULLABLE: '', //可空, Y/N, 前端叫 非空, 要取反
  })

function handleAddRow(){
    var obj = Object.assign({ }, ColumnDefalut.value)
    
    var cn = 'column1'
    for(var ci = 0; ci < dataForm.value.Columns.length + 1; ci++) {
        cn = 'column' + (ci + 1)
        if(dataForm.value.Columns.filter(o => o.COLUMN_NAME == cn).length == 0)
            break;
    }
    obj.COLUMN_NAME = cn
    dataForm.value.Columns.push(obj)
}
function handleRemove(scope){
    dataForm.value.Columns.splice(dataForm.value.Columns.indexOf(scope.row), 1)
}
function submitForm() {
    if(!dataForm.value.TABLE_NAME) {
        ElMessage({ 
            message: '表名是必填项',
            type: 'error',
        })
        return;
    }
    if(dataForm.value.Columns.length == 0) {
        ElMessage({ 
            message: '表至少包含一列',
            type: 'error',
        })
        return;
    }
    if(dataForm.value.Columns.filter(o => o.ISKEY == 1 && o.AUTOIN == 1).length > 1) {
        ElMessage({ 
            message: '不允许多个自增列',
            type: 'error',
        })
        return;
    }
    var param = Object.assign(dataForm.value, {
        dbName: dbName.value,
        DbType: 'Sqlite',
        dbConnStr: dbConnStr.value,
    })
    post(`/api/${param.DbType}/Edit`, param)
    .then((res) => {
        if(!res.flag) {
            ElMessage({ 
                message: res.msg,
                type: 'error',
            })
            return;
        }
        ElMessage({ 
            message: '保存成功',
            type: 'success',
        })
        emit('update:show', false)
    })
}

onMounted(()=> {
  console.log('SqliteDesign mounted')
})

const oldForm = JSON.stringify(dataForm.value)
watch(() => show.value, (val, oldval) => {
  if(val && tableName.value){ //显示且是编辑状态
    dataForm.value.TABLE_NAME = tableName.value
    var param = { 
        DbType: 'Sqlite',
        DbName: dbName.value,
        DbConnStr: dbConnStr.value,
        TABLE_NAME: dataForm.value.TABLE_NAME
    }
    post(`/api/${param.DbType}/GetTable`, param)
    .then((res) => {
        res.forEach(row => row.EDIT_COLUMN_NAME = row.COLUMN_NAME)
        dataForm.value.Columns = res
        dataForm.value.EDIT_TABLE_NAME = dataForm.value.TABLE_NAME
    })
  } else {
    dataForm.value = JSON.parse(oldForm)
  }
})
</script>
